import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Container,
  Paper,
  Typography,
  Button,
  Grid,
  Box,
  Alert,
  Divider,
} from '@mui/material';
// 使用 qrcode.react 需要先安装依赖：npm install qrcode.react @types/qrcode.react
import { QRCodeSVG } from 'qrcode.react';
import { format } from 'date-fns';
import { apiRequest, API_PATHS } from '../config/api';

interface Order {
  _id: string;
  quantity: number;
  totalPrice: number;
  status: 'completed' | 'cancelled';
  createdAt: string;
  movie: {
    title: string;
    showtime: string;
    price: number;
  };
}

const OrderDetail: React.FC = () => {
  const { orderId } = useParams<{ orderId: string }>();
  const navigate = useNavigate();
  const [order, setOrder] = useState<Order | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchOrderDetail = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          setError('请先登录');
          return;
        }

        const data = await apiRequest<any>(API_PATHS.ORDER_DETAIL(orderId));

        // 转换数据结构以匹配组件期望的格式
        const formattedOrder = {
          _id: data._id,
          quantity: data.quantity,
          totalPrice: data.totalPrice,
          status: data.status,
          createdAt: data.createdAt,
          movie: {
            title: data.movieId.title,
            showtime: data.movieId.showtime,
            price: data.movieId.price
          }
        };

        setOrder(formattedOrder);
      } catch (error) {
        setError('获取订单详情失败');
      }
    };

    if (orderId) {
      fetchOrderDetail();
    }
  }, [orderId]);

  const handleBack = () => {
    navigate('/orders');
  };

  if (!order || !order.movie) {
    return (
      <Container>
        <Box sx={{ mt: 4 }}>
          {error ? (
            <Alert severity="error">{error}</Alert>
          ) : (
            <Typography>加载中...</Typography>
          )}
        </Box>
      </Container>
    );
  }

  // 生成二维码数据
  const qrCodeData = JSON.stringify({
    orderId: order._id,
    movieTitle: order.movie.title,
    showtime: order.movie.showtime,
    quantity: order.quantity,
    status: order.status
  });

  return (
    <Container maxWidth="md">
      <Button
        variant="outlined"
        onClick={handleBack}
        sx={{ mt: 4, mb: 2 }}
      >
        返回订单列表
      </Button>

      <Paper 
        sx={{
          mt: 2,
          p: 0,
          bgcolor: '#fff',
          borderRadius: '16px',
          overflow: 'hidden',
          position: 'relative',
          '&::before': {
            content: '""',
            position: 'absolute',
            left: 0,
            top: '50%',
            width: '20px',
            height: '20px',
            bgcolor: '#f5f5f5',
            borderRadius: '50%',
            transform: 'translate(-50%, -50%)',
            boxShadow: 'inset -1px 0 5px rgba(0,0,0,0.1)',
            zIndex: 1
          },
          '&::after': {
            content: '""',
            position: 'absolute',
            right: 0,
            top: '50%',
            width: '20px',
            height: '20px',
            bgcolor: '#f5f5f5',
            borderRadius: '50%',
            transform: 'translate(50%, -50%)',
            boxShadow: 'inset 1px 0 5px rgba(0,0,0,0.1)',
            zIndex: 1
          }
        }}
      >
        <Box sx={{
          borderBottom: '2px dashed #e0e0e0',
          bgcolor: '#1976d2',
          color: 'white',
          p: 3,
          textAlign: 'center'
        }}>
          <Typography variant="h4" gutterBottom sx={{ fontWeight: 'bold' }}>
            {order.movie.title}
          </Typography>
          <Typography variant="h6">
            {format(new Date(order.movie.showtime), 'yyyy-MM-dd HH:mm')}
          </Typography>
        </Box>

        <Grid container>
          <Grid item xs={12} md={8} sx={{
            p: 4,
            borderRight: { md: '2px dashed #e0e0e0' },
            position: 'relative'
          }}>
            <Box sx={{ mb: 3 }}>
              <Typography variant="body1" sx={{ mb: 2, color: '#666' }}>
                订单编号：{order._id}
              </Typography>
              <Typography variant="h6" sx={{ mb: 1, fontWeight: 'bold' }}>
                票价信息
              </Typography>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography>单价</Typography>
                <Typography>¥{order.movie.price.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography>数量</Typography>
                <Typography>{order.quantity}张</Typography>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>总价</Typography>
                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>¥{order.totalPrice.toFixed(2)}</Typography>
              </Box>
            </Box>

            <Box>
              <Typography variant="h6" sx={{ mb: 2, fontWeight: 'bold' }}>
                订单状态
              </Typography>
              <Box sx={{
                display: 'inline-block',
                px: 2,
                py: 0.5,
                borderRadius: '4px',
                bgcolor: order.status === 'completed' ? '#e8f5e9' : '#ffebee',
                color: order.status === 'completed' ? '#2e7d32' : '#d32f2f'
              }}>
                {order.status === 'completed' ? '已完成' : '已取消'}
              </Box>
              <Typography sx={{ mt: 2, color: '#666' }}>
                下单时间：{format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm')}
              </Typography>
            </Box>
          </Grid>

          <Grid item xs={12} md={4} sx={{ p: 4, bgcolor: '#fafafa' }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', fontWeight: 'bold' }}>
              入场验证
            </Typography>
            <Box sx={{
              display: 'flex',
              justifyContent: 'center',
              mb: 2,
              p: 3,
              bgcolor: 'white',
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}>
              <QRCodeSVG
                value={qrCodeData}
                size={180}
                level="H"
                includeMargin
                style={{ maxWidth: '100%', height: 'auto' }}
              />
            </Box>
            <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center' }}>
              请向工作人员出示此二维码进行核销
            </Typography>
          </Grid>
        </Grid>
      </Paper>
    </Container>
  );
};

export default OrderDetail;